import { getToken, setToken, removeToken } from '@/utils/storage'
import { login as loginApi, logout, user as userApi } from '@/api/user'
// import { Message } from 'element-ui'


const state = {
  token: getToken(),
  userInfo:{}
}
const mutations = {
  updateToken(state, token) {
    state.token = token
    // 再存到本地
    setToken(token)
  },
  delToken(state) {
    state.token = null
    // 删除vuex的token
    removeToken()
  },
  updateUserInfo (state, payload) {
    state.userInfo = payload
  }
}
const actions = {
  // context上下文，传入参数
  async login(context, data) {
    console.log('调用了登录接口', data)
    const res = await loginApi(data)
    console.log(res);
    // 返回一个token 1
    context.commit('updateToken', res.token)
  },
  async getUserInfo ({commit}) {
    // console.log(id)
    const  res = await userApi()
   commit('updateUserInfo',res)
  },
  async logout({commit}) {
      commit('delToken')   // 退出
      commit('updateUserInfo', {}) // 设置用户信息为空对象
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
